package com.zsp.springcloud.microservice.consumer.service.impl;

import com.zsp.springcloud.microservice.consumer.domain.User;
import com.zsp.springcloud.microservice.consumer.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Created by 01204808 on 2017/8/11.
 */
@Component
public class UserService implements IUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public User getUserById(Long id) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("microservice-provider");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }
}
